#-*- coding: utf-8 -*-
from google.appengine.ext import db

import datetime
import generalcounter

from logics.main import get_user, set_user
import re

class App_user(db.Model):
    email = db.EmailProperty(required = True)
    nickname = db.StringProperty(required = True)
    link = db.StringProperty()

    level = db.IntegerProperty()

    password = db.StringProperty()

    is_verified = db.BooleanProperty(required = True)

    comment_count = db.IntegerProperty(default=0)
    post_count = db.IntegerProperty(default=0)

    add_time = db.DateTimeProperty(required = True)

class Post(db.Model):
    offset = db.IntegerProperty(required = True) #递增
    title = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    author = db.ReferenceProperty(App_user, collection_name = 'add_post_set', required = True)
    summary = db.TextProperty()

    add_time = db.DateTimeProperty(required = True)

    modify_time = db.DateTimeProperty()
    modify_user = db.ReferenceProperty(App_user, collection_name = 'modify_post_set')

    comment_count = db.IntegerProperty(default=0)
    tags = db.StringListProperty()

    is_delete = db.BooleanProperty(default = False)
    delete_user = db.ReferenceProperty(App_user, collection_name = 'delete_post_set')
    
    @classmethod
    def all(cls):
        #now = datetime.datetime.utcnow()
        return super(Post, cls).all().filter('is_delete', False)

    @classmethod
    def count(cls):
        return int(generalcounter.get_count('post'))

    @classmethod
    def add(cls, title, content, summary = None, add_time = None):
        u = get_user()
        count = cls.count()
        if add_time is None:
            add_time = datetime.datetime.utcnow()
        p = cls(parent =u, offset = count+1, title = title, content = content, \
                author = u, add_time = add_time)
        if summary:
            p.summary = summary
        
        u.post_count += 1

        def txn():
            p.put()
            u.put()
        db.run_in_transaction(txn)
        generalcounter.increment('post')
    
    def modify(self, title, content, summary = None, add_time = None):
        u = get_user()
        self.title = title
        self.content = content
        self.summary = summary
        if add_time:
            self.add_time = add_time
        
        self.modify_time = datetime.datetime.utcnow()
        self.modify_user = u
        self.put()

    def delete(self):
        u = get_user()
        def txn():
            #super(Post, self).delete()
            self.is_delete = True
            self.delete_user = u
            self.author.post_count -= 1
            self.put()
            self.author.put()

        db.run_in_transaction(txn)
        generalcounter.decrement('post')
    
    @classmethod
    def get_list(cls, page, page_size):
        q = cls.all()
        q.order('-offset')
        return q.fetch(page_size, offset = page_size*(page-1))
    
    def get_comment_list(self):
        return Comment.all().filter('post', self).order('add_time').fetch(100)
    
    def to_atom_xml(self):
        sep = '<hr class="more">'
        return re.sub('&(?!amp;)', '&amp;', self.content).replace(sep, '')

class Comment(db.Model):
    email = db.EmailProperty()
    nickname = db.StringProperty()

    author = db.ReferenceProperty(App_user)

    post = db.ReferenceProperty(Post, required = True)

    link = db.StringProperty()
    content = db.TextProperty()
    ip = db.StringProperty()
    add_time = db.DateTimeProperty()

    is_delete = db.BooleanProperty(default = False)
    delete_user = db.ReferenceProperty(App_user, collection_name = 'delete_comment_set')
    
    @classmethod
    def all(cls):
        return super(Comment, cls).all().filter('is_delete', False)

    @classmethod
    def auth_add(cls, post, content, ip, author_nickname = None, link = None):
        return cls._add(post, content, ip, author_email = None, \
                author_nickname = author_nickname, link = link)
    
    @classmethod
    def anonymous_add(cls, post, content, ip, author_email, author_nickname, link = None):
        return cls._add(post, content, ip, author_email = author_email, \
                author_nickname = author_nickname, link = link)

    @classmethod
    def _add(cls, post, content, ip, author_email = None, author_nickname = None, link = None):
        u = get_user()
        if author_email is None:
            #登录用户发帖
            c = cls(parent = post, email = u.email, nickname = u.nickname, author = u, post = post, \
                    content = content, ip = ip, add_time = datetime.datetime.utcnow())
            if link and u.link != link:
                u.link = link
            if author_nickname and author_nickname != u.nickname:
                u.nickname = author_nickname
                c.nickname = author_nickname
        else:
            c = cls(parent = post, email = author_email, nickname = author_nickname, post = post, \
                    content = content, ip = ip, add_time = datetime.datetime.utcnow())
        if link:
            c.link = link
        
        def txn():
            c.put()
            post.comment_count += 1
            if author_email is None:
                u.comment_count += 1
                u.put()
            post.put()
        db.run_in_transaction(txn)
    
    def delete(self):
        u = get_user()
        def txn():
            self.is_delete = True
            self.delete_user = u
           
            self.post.comment_count -= 1

            self.put()
            self.post.put()
            if self.author:
                self.author.comment_count -= 1
                self.author.put()
        db.run_in_transaction(txn)

class Tag(db.Model):
    tag = db.StringProperty()
    post_count = db.IntegerProperty(default=0)

class Sidebar(db.Model):
    title = db.StringProperty(required = True)
    content = db.TextProperty(required = True)
    order = db.IntegerProperty(required = True, default= 0)
    add_time = db.DateTimeProperty(auto_now_add = True)
